
var NQTSort = new function () {
    var _gridId;
    var _requestDataFunction;
    this.Init = function (gridId, requestDataFunction) {
        _requestDataFunction = requestDataFunction;
        _gridId = gridId;
        $("th.sortable", "#" + gridId).on("click", function (e) {
            eventHandler(e);
        });
    };

    this.RequestData = function () {
        var sortData = new Object();
        var sortItemCount = 0;
        $("th.sortable", "#" + _gridId).each(function() {
            var sortIconElement = $(this).find('span.sorticon');
            if (sortIconElement.hasClass('none')) return;

            sortItemCount++;
            sortData['sortExpression' + sortItemCount] = $(this).attr('role');
            sortData['sortOrder' + sortItemCount] = $("p:first-child", sortIconElement).html();
        });
        sortData['sortLength'] = sortItemCount;
        if (_requestDataFunction) _requestDataFunction(sortData);
    };
   
    function eventHandler(eventArg) {
        var target = eventArg.target, // e.target grabs the node that triggered the event.
           $target = $(target);  // wraps the node in a jQuery object
        // Sorting
        var $sortColumn = $target.parent();
        if (target.nodeName === "SPAN" && $sortColumn[0].nodeName === "TH" && $sortColumn.hasClass('sortable')) {
            buildSort($sortColumn, $sortColumn.find('span.sorticon'));
            return;
        }
    }
    var sortOrders = [['sorticon asc', 'Ascending', 'asc'], ['sorticon desc', 'Descending', 'desc'], ['sorticon none', 'Sorting', 'None']];
    function buildSort($headerColumn, $sortNode) {
        var $sortStatus = $sortNode.find("p:first-child");
        var currentStatus = $sortStatus.html();
        var nextSortIndex;
        switch (currentStatus) {
            case 'asc':
                nextSortIndex = 1;
                break;
            case 'desc':
                nextSortIndex = 2;
                break;
            default:
                nextSortIndex = 0;
                break;
        }
        $sortNode.attr('class', sortOrders[nextSortIndex][0]);
        $sortNode.attr('title', sortOrders[nextSortIndex][1]);
        $sortStatus.html(sortOrders[nextSortIndex][2]);
        NQTSort.RequestData();
    }
   
};
